package com.sky.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@Slf4j
@EnableCaching
public class RedisConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("开始创建redis模板对象...");
        RedisTemplate redisTemplate = new RedisTemplate();
        //设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis key的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 默认的缓存过期配置，设置缓存默认过期时间为4小时
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(4)); // 设置过期时间为4小时
//                .disableCachingNullValues();  // 禁用缓存空值

        // 为特定的缓存键（例如 "SHOP_STATUS"）设置没有过期时间的配置
        RedisCacheConfiguration shopStatusCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ZERO);  // 设置过期时间为零，意味着不设置过期时间
//                .disableCachingNullValues(); // 禁用缓存空值

        // 创建 RedisCacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(defaultCacheConfig)  // 默认缓存配置
                .withCacheConfiguration("SHOP_STATUS", shopStatusCacheConfig)  // 针对 "SHOP_STATUS" 配置无过期时间
                .build();

        return cacheManager;
    }
}
